package testJdk.base.juc_test.test_lock;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName : learn_jdk.base.juc_test.test_lock.LockTest
 * @Description : 类描述
 * Created by cyd on 2021-10-24 17:12:32
 */
public class LockTest {

    public static void main(String[] args) {
        LockTestTask task = new LockTestTask();
        new Thread(task, "1号售票厅").start();
        new Thread(task, "2号售票厅").start();
        new Thread(task, "3号售票厅").start();
    }
}

class LockTestTask implements Runnable {

    private int ticketNum = 100;
    private final Lock lock = new ReentrantLock();

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            // 在while循环里面加锁，
            // 因为while循环太快，如果加在外面，其他线程访问时会有IllegalMonitorStateException异常
            lock.lock();

            try {
                if (ticketNum > 0) {
                    // 此处是为了方法问题
                    Thread.sleep(200);
                    System.out.println(Thread.currentThread().getName() +
                            " 完成售票，余票为：" + --ticketNum);
                }
            } finally {
                // 释放锁的操作，必须写在finally中，否则一旦报错，会导致线程死锁
                lock.unlock();
            }
        }
    }
}

